package com.redstar.HappyRefresh.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniu.storage.model.FileInfo;
import com.redstar.HappyRefresh.config.QiNiuConfig;
import com.redstar.HappyRefresh.mapper.FileMapper;
import com.redstar.HappyRefresh.pojo.File;
import com.redstar.HappyRefresh.service.FileService;
import com.redstar.HappyRefresh.service.QiNiuFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import ws.schild.jave.MultimediaObject;
import ws.schild.jave.info.MultimediaInfo;
import ws.schild.jave.process.ffmpeg.FFMPEGProcess;

import java.net.URL;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Autowired
    private QiNiuFileService qiNiuFileService;

    @Override
    public Long generatePhoto(Long fileId, Long userId) { // 根据视频的id获取封面图片
        File file = this.getById(fileId);
        // 根据文件的url截取封面图片
        String fileKey = file.getFileKey() + "?vframe/jpg/offset/1";
        File fileInfo = new File();
        fileInfo.setFileKey(fileKey);
        // 文件格式，也就是视频分类
        fileInfo.setFormat("image/*");
        fileInfo.setType("图片");
        fileInfo.setUserId(userId);
        save(fileInfo);
        return fileInfo.getId();
    }

    @Override
    public String getVideoDuration(String fileUrl) { // 获取视频时长
        String[] length = new String[2];
        try {
            // 获取视频的多媒体信息
            URL source = new URL(fileUrl);
            MultimediaObject instance = new MultimediaObject(source);
            MultimediaInfo result = instance.getInfo();
            // 获取视频时长，将毫秒转化为秒
            Long ls = result.getDuration() / 1000;
            length[0] = String.valueOf(ls);
            int hour = (int) (ls / 3600);
            int minute = (int) (ls % 3600) / 60;
            int second = (int) (ls - hour * 3600 - minute * 60);
            String hr = Integer.toString(hour);
            String mi = Integer.toString(minute);
            String se = Integer.toString(second);
            // 将视频时长地格式化为 HH:mm:ss 或 mm:ss 的字符串形式
            if (hr.length() < 2) {
                hr = "0" + hr;
            }
            if (mi.length() < 2) {
                mi = "0" + mi;
            }
            if (se.length() < 2) {
                se = "0" + se;
            }
            String noHour = "00";
            if (noHour.equals(hr)) {
                length[1] = mi + ":" + se;
            } else {
                length[1] = hr + ":" + mi + ":" + se;
            }
        } catch (Exception e) {
            throw new RuntimeException("getVideoDuration方法出错：" + e.getMessage());
        }
        return length[1];
    }

    @Override
    public File getFileTrustUrl(Long fileId) { // 获取文件真实的url
        File file = getById(fileId);
        if (!ObjectUtils.isEmpty(file)) {
            // 生成随机字符串
            String s = UUID.randomUUID().toString();
            // 拼接七牛云的别名记录和文件的url
            String url = QiNiuConfig.CNAME + "/" + file.getFileKey();
            // 拼接随机生成的字符串
            if (url.contains("?")) {
                url = url + "&uuid=" + s;
            } else {
                url = url + "?uuid=" + s;
            }
            file.setFileKey(url);
            return file;
        } else {
            log.info("getFileTrustUrl方法：未找到该文件");
            return null;
        }

    }

    @Override
    public Long saveFile(String fileKey, Long userId) { // 保存文件，根据文件的url获取文件信息，然后写入数据库，返回文件id
        // 根据URL获取文件信息
        FileInfo fileInfo = qiNiuFileService.getFileInfo(fileKey);
        String mimeType = fileInfo.mimeType; // 文件性质
        long size = fileInfo.fsize; // 文件大小
        File file = new File();
        file.setFileKey(fileKey); // 文件url
        file.setFormat(mimeType); // 文件的性质
        file.setSize(size); // 文件大小
        file.setUserId(userId); // 用户id
        file.setType(mimeType.contains("video") ? "视频" : "图片"); // 文件类型
        // 写入数据库
        this.save(file);
        // 返回文件id
        return file.getId();
    }
}
